// server.js
const express = require('express')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const app = express()

// 中间件
app.use(express.json())

// 模拟数据库
let users = []
let messages = []

// 用户注册
app.post('/api/register', async (req, res) => {
  const { username, password } = req.body
  
  // 验证用户是否存在
  if (users.some(u => u.username === username)) {
    return res.status(400).json({ code: 400, message: '用户名已存在' })
  }

  // 密码加密
  const hashedPassword = await bcrypt.hash(password, 10)
  const newUser = {
    id: Date.now(),
    username,
    password: hashedPassword
  }
  
  users.push(newUser)
  res.status(201).json({ code: 200, message: '注册成功' })
})

// 用户登录
app.post('/api/login', async (req, res) => {
  const { username, password } = req.body
  const user = users.find(u => u.username === username)

  if (!user || !await bcrypt.compare(password, user.password)) {
    return res.status(401).json({ code: 401, message: '用户名或密码错误' })
  }

  // 生成JWT令牌
  const token = jwt.sign(
    { userId: user.id }, 
    'YOUR_SECRET_KEY',
    { expiresIn: '2h' }
  )

  res.json({ code: 200, message: '登录成功', token })
})

// 留言提交
app.post('/api/messages', authenticateToken, (req, res) => {
  const { content } = req.body
  const newMessage = {
    id: Date.now(),
    userId: req.user.userId,
    content,
    timestamp: new Date()
  }
  messages.push(newMessage)
  res.status(201).json({ code: 200, message: '留言成功' })
})

// 认证中间件
function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization']
  const token = authHeader && authHeader.split(' ')[1]
  
  if (!token) return res.sendStatus(401)

  jwt.verify(token, 'YOUR_SECRET_KEY', (err, user) => {
    if (err) return res.sendStatus(403)
    req.user = user
    next()
  })
}

app.listen(3000, () => console.log('Server running on port 3000'))